<script setup lang="ts">
import { reactive } from 'vue';
import { Search, Plus, Promotion } from '@element-plus/icons-vue'
import { SerachConfig } from '../interfaceType';
import { pageStore } from '@/store/modules/pageConfig'
const configStore = pageStore()


defineProps({
    msg: String,
    list: Object
})

interface searchForm extends SerachConfig {
    searchTypeCollapse: boolean,
    candidateCollapse: boolean,
    addFlag: boolean
}

let searchForm = ref<searchForm>({
    ...configStore.serach,
    key: "",
    searchTypeCollapse: false,
    candidateCollapse: false,
    addFlag: false,
})

let searchItem = reactive({
    name: '',
    url: ''
})

let searchTypeList = ref<any>([
    ...configStore.searchTypeList
])

let searchTypeListTemp = ref<any>([
    { name: '百度', uri: 'https://www.baidu.com/s?ie=UTF-8&wd=%s', icon: 'https://www.baidu.com/favicon.ico', show: true },
    { name: '必应', uri: 'https://cn.bing.com/search?q=%s', icon: '', show: true },
    { name: '百3度', uri: 'https://www.baidu.com', icon: '', show: false }
])

const autoCompleteRef = ref<HTMLDivElement | any>('')
const searchEngineListRef = ref<HTMLDivElement>()
watch(() => autoCompleteRef.value.highlightedIndex, () => {
    if (autoCompleteRef.value.highlightedIndex >= 0) {
        searchForm.value.key = candidate.value?.g[autoCompleteRef.value.highlightedIndex]?.q
    }
})


let t: any = null      // 防抖
function openSearchType() {
    autoCompleteRef.value?.close()
    if (t == null) {
        searchForm.value.searchTypeCollapse = !searchForm.value.searchTypeCollapse
    }
    t = 1
    setTimeout(() => {
        t = null
    }, 100)
    setTimeout(() => {
        if (searchForm.value.searchTypeCollapse) {
            const contextMenu = searchEngineListRef.value as HTMLDivElement
            contextMenu.focus()
        }
    }, 50)
}


function chooseSearchType(item: SerachConfig) {
    searchForm.value.uri = item.uri
    searchForm.value.icon = item.icon
    searchForm.value.name = item.name
    configStore.setSerachType(item)
    searchForm.value.searchTypeCollapse = false
}

//搜索框回车
function searchInputChange() {
    if (searchForm.value.key?.length == 0) return
    let url = searchForm.value.uri.split('%s').join(searchForm.value.key)
    window.open(url)
}


function addSearchType() {
    searchTypeList.value.push({ name: searchItem.name, uri: searchItem.url, icon: '', show: true })
    searchItem.name = ''
    searchItem.url = ''
    configStore.setSearchTypeList(searchTypeList.value)
    searchForm.value.addFlag = false
}


onMounted(() => {
    //初始化搜索引擎
    if (searchTypeList.value.length == 0) {
        searchTypeList.value = searchTypeListTemp.value
    }
    // autoCompleteRef.value.handleSelect = () => {
    //     searchInputChange()
    // }
    // autoCompleteRef.value.handleKeyEnter = () => {
    //     searchInputChange()
    // }

})

let candidate = ref<any>()

const querySearch = (queryString: string, cb: any) => {
    let newValue = queryString.trim()
    if (newValue.length > 0) {
        let url = 'https://www.baidu.com/sugrec?ie=utf-8&json=1&prod=pc&from=pc_web&wd=' + queryString
        ajaxRequest.get({ url: url }).then(res => {
            candidate.value = res
            cb(res.g)
        })
    }
}

</script>

<template>
    <div>
        <el-autocomplete ref="autoCompleteRef" v-model="searchForm.key" :fetch-suggestions="querySearch" clearable
            placeholder="Please Input" popper-class="my-autocomplete">
            <template #prefix>
                <div @click.prevent.stop="openSearchType" @mousedown.stop class="search-input-icon custom-icon">
                    <el-avatar style="margin: 5px;" class="saerch_icon" :src="searchForm.icon"> {{ searchForm.name }}
                    </el-avatar>
                </div>
            </template>
            <template #suffix>
                <el-button size="small" circle style="border: unset;font-size: 25px;" title="搜索"
                    @click="searchInputChange">
                    <template #icon>
                        <Search color="red" />
                    </template>
                </el-button>
            </template>
            <template #default="{ item }">
                <div class="value">{{ item.q }}</div>
            </template>
        </el-autocomplete>
        <el-row>
            <el-col :span="24">
                <el-collapse-transition>
                    <div v-show="searchForm.searchTypeCollapse" class="search_engine_list" ref="searchEngineListRef"
                        tabindex="-1" @blur.native.capture="searchForm.addFlag ? '' : openSearchType()">
                        <slot v-for="(item, index) in searchTypeList" :index="index">
                            <div class="transition-box" v-if="item.show" @click.prevent="chooseSearchType(item)">
                                <div class="search-item">
                                    <el-avatar shape="square" :size="50" class="search-icon" :src="item.icon">{{
                                        item.name
                                        }}</el-avatar>
                                    <span class="search-title">
                                        {{ item.name }}
                                    </span>

                                </div>
                            </div>
                        </slot>
                        <div class="transition-box">
                            <div class="search-item add" @click="() => { searchForm.addFlag = true }">
                                <el-avatar shape="square" :size="50" class="search-icon" :icon="Plus" />
                                <span class="search-title">
                                    添加
                                </span>

                            </div>
                        </div>
                    </div>
                </el-collapse-transition>
            </el-col>
        </el-row>

        <el-dialog v-model="searchForm.addFlag" title="" width="500" :append-to-body="true">
            <div class="transition-box">
                <div class="search-item add" @click="() => { searchForm.addFlag = true }">
                    <el-avatar shape="square" :size="50" class="search-icon" :icon="Plus"
                        :src="'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'" />
                    <!-- <span class="search-title">
                        添加
                    </span> -->
                </div>
            </div>
            <div>
                <el-form :model="searchItem" label-width="80px">
                    <el-form-item label="名称">
                        <el-input v-model="searchItem.name" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="网址">
                        <el-input v-model="searchItem.url" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }"
                            placeholder="Please input" autocomplete="off"></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="searchForm.addFlag = false" title="取消">取消</el-button>
                    <el-button type="primary" @click="addSearchType" title="保存">
                        保存
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<style scoped lang="scss">
/** 搜索框 */
:deep(.el-input__wrapper) {
    border-radius: 50px;
    padding-right: 20px;
}

:deep(.el-input__suffix-inner) {
    flex-direction: row-reverse;
}

:deep(.el-input__clear) {
    font-size: 25px;
}

:deep(.el-popper__arrow) {
    display: none;
}

.search-input-icon {
    display: flex;
    align-items: center;
    margin-left: 1px !important;

    .el-avatar {
        // --el-avatar-bg-color:unset;
    }

    .el-avatar--circle:hover {
        box-shadow: 0px 0 6px 0px #909399;
        border-radius: 50%;
    }
}


.search_engine_list {
    font-size: 13px;
    margin-top: 10px;
    position: absolute;
    z-index: 2;
    width: 100%;
    background-color: #d7d7d7;
    border-radius: 10px;
    box-shadow: var(--el-box-shadow-dark);
    display: grid;
    justify-content: space-around;
    grid-template-columns: repeat(auto-fill, 70px);
    row-gap: 10px;
    column-gap: 5px;
    grid-auto-flow: dense;

    & .transition-box {
        padding: 10px 0;

        & .search-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;

            & span.search-icon:hover {
                box-shadow: 0px 0 6px 0px #909399;
            }
        }

        & .add {
            & span.search-icon {
                background-color: rgb(255 255 255 / 50%);
                color: black;
            }
        }



    }
}

.candidate_list {
    font-size: 14px;
    margin-top: 10px;
    position: absolute;
    z-index: 2;
    width: 100%;
    background-color: #d7d7d7;
    border-radius: 10px;
    box-shadow: var(--el-box-shadow-dark);
    text-align: left;
    overflow: hidden;

    & .transition-box {
        &:hover {
            background-color: rgb(255 255 255 / 50%);
        }

        & .candidate-item {
            padding: 5px 10px;
        }
    }
}

.el-dialog__body {
    & .transition-box {
        & .add {
            display: flex;
            justify-content: center;
            align-items: center;
            padding-bottom: 15px;

        }
    }
}
</style>